/**
 * 应用主入口
 **/

// React Libs
import React, { Fragment } from 'react'
// Components
import Portals from './components/Portals'
import Wrapper from './components/Wrapper'
// Config
import { defProp } from './config/default'

export default class ReactZmage extends React.PureComponent<any, any> {
    cover = null
    constructor(props: any){
        super(props)
        // States
        this.state = {
            browsing: false,
            set: this.buildSet(props)
        }

    }
    componentWillReceiveProps (newProps: any) {
        const { set } = this.state
        let buildSet = this.buildSet(newProps) 
        if(JSON.stringify(set) !== JSON.stringify(buildSet)) {
            this.setState({
                ...this.state,
                set: buildSet
            })
        }
    }
    // 从初始 props 中生成图片集合
    buildSet = (props: any) => {
        const { set, src, alt, txt } = props
        if(set && set.constructor===Array && set.length>1) {
            return set
        } else {
            return [{ src, alt, txt }]
        }
    }

    // 切换查看状态
    browsing = () => {
        const { onClick } = this.props
        onClick && onClick.constructor===Function && onClick()
        this.setState({ browsing: true })
    }
    unBrowsing = () => {
        this.setState({ browsing: false })
    }

    render() {
        const { browsing, set } = this.state
        const {
            className, src, alt,  // 基本属性
            controller,           // 页面按钮
            hotKey,               // 热键
            style,                // 样式
            ...props              // 剩余参数
        } = this.props
        return (
            <Fragment>

                {/*封面图片*/}
                <img
                    ref={(ref: any) => this.cover = ref}
                    className={className} src={src} alt={alt} title={alt}
                    style={{ cursor:'zoom-in', ...style }}
                    onClick={this.browsing}
                    {...props}
                />

                {/*查看叠层*/}
                {
                    browsing &&
                    <Portals>
                        <Wrapper
                            set={set}
                            cover={this.cover}
                            controller={{ ...defProp.controller, ...controller }}
                            hotKey={{ ...defProp.hotKey, ...hotKey }}
                            remove={this.unBrowsing}
                        />
                    </Portals>
                }

            </Fragment>
        )
    }
}